import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import CoreLayout from 'containers/layout'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { getDataSource, getFlagValue, showTeam, getTeamFlag, getPageFlag } from 'services/utils'
import { Form, Input, InputNumber, DatePicker, Divider, Button, Select, Radio, Row, Col, Tooltip, Icon, message } from 'antd'
import TagSelect from 'ant-design-pro/lib/TagSelect'
import { ItemSelect } from '../../components'
import { protoActions } from 'reduxs'
import _ from 'lodash'
import moment from 'moment'
import 'ant-design-pro/dist/ant-design-pro.css'
import 'styles/account.scss'

const FormItem = Form.Item
const Option = Select.Option
const RadioGroup = Radio.Group
const RadioButton = Radio.Button
const TextArea = Input.TextArea
const accessFlag = getPageFlag('/system-tools/proto', 'access')

@connect(
  state => ({
    auth                : state.Passport.auth,
    teams               : state.Passport.teams,
    rtsp_key            : state.Passport.rtsp_key,
    listData            : state.Proto.listData,
    getListPending      : state.Proto.getListPending,
    postDataPending     : state.Proto.postDataPending,
    postDataError       : state.Proto.postDataError,
    postDataMessage     : state.Proto.postDataMessage,
    MODIFY_ROLE_TYPE    : state.Proto.MODIFY_ROLE_TYPE,
    items               : state.Proto.items,
    paths               : state.Proto.paths,
    srv                 : state.Proto.srv,
    rooms               : state.Proto.rooms,
    roomfish            : state.Proto.roomfish
  }),
  dispatch => ({
    actions: bindActionCreators({ 
      ...protoActions
    }, dispatch)
  })
)
@Form.create()
class AdvancedSearchForm extends PureComponent {

  constructor (props) {
    super(props)
    this.state = {
      protoName: undefined
    }
  }

  componentDidMount () {
    this.props.actions.getlist()
  }
  
  componentWillReceiveProps (nextProps) {
    const { postDataError, postDataMessage } = nextProps
    if (postDataError > 0 && postDataError !== this.props.postDataError) {
      message.warn(postDataMessage || '请求被终止')
    }
  }

  render () {
    const { location, auth, teams, rtsp_key, form, listData, getListPending, postDataPending, MODIFY_ROLE_TYPE, items, paths, srv, rooms, roomfish } = this.props
    const { getFieldDecorator } = form
    let Options = {
      ['MODIFY_ROLE_TYPE']: MODIFY_ROLE_TYPE,
      ['paths']: paths,
      ['srv']: srv,
      ['rooms']: rooms,
      ['roomfish']: roomfish
    }
    let protoAPI = null
    let protoParams = null
    let protoOptions = null
    let divOptions = null
    if (this.state.protoName && listData) {
      protoAPI = _.find(listData, o => o.name === this.state.protoName)
      protoParams = protoAPI.params
      protoOptions = protoAPI.options || {}
      if (/(content)/.test(_.values(protoParams).join(','))) {
        divOptions = {
          style: { flexDirection: 'column' }
        }
      }
    }
    //console.log(/(\?)(\S+)$/.test('user-info'))
    //console.log(/(\?)(\S+)$/.test('user-info?test'))
    // flex-direction: column;
    return (
      <Form
        className="ant-advanced-search-form"
        onSubmit={this.handleSubmit}
        >
        <FormItem 
          label={(<span style={{ width: 80, display: 'inline-block' }}>PROTO 接口</span>)}
          >
          {getFieldDecorator('proto', {
            rules: [{ required: true, message: `请选择 PROTO 接口!` }]
          })(
            <Select 
              placeholder="请选择 PROTO 接口..." 
              size="Small"
              //mode="multiple"
              style={{ width: '350px' }}
              onChange={this.handleChangeProto}
              >
              {listData && listData.map((item, i) => {
                return (
                <Option key={i} value={item.name}>[{item.code}] {item.key}</Option>
                )
              })}
            </Select>
          )}
          <span style={{ marginLeft: 50, color: '#c00' }}>{protoAPI && protoAPI.message}</span>
        </FormItem>
        <Divider dashed />
        <div className="content" {...divOptions}>
          {protoParams && _.keys(protoParams).map((item, i) => {
            if (/(tagselect)/.test(protoParams[item])) {
              let params = _.isString(protoOptions[item]) ? Options[protoOptions[item]] : protoOptions[item]
              return (
                <FormItem 
                  label={(<span style={{ width: 80, display: 'inline-block' }}>{item}</span>)}
                  required={false}
                  >
                  {getFieldDecorator(item, {
                    rules: !/^(\!)/.test(protoParams[item]) ? [{ required: true, message: `${item} 不能为空!` }] : []
                  })(
                    <TagSelect expandable style={{ marginTop: 6, marginLeft: 10 }}>
                      {_.keys(params).sort().map((key, i) => {
                        return (
                        <TagSelect.Option key={i} value={key}>{params[key]}</TagSelect.Option>
                        )
                      })}
                    </TagSelect>
                  )}
                </FormItem>
              )
            }
            else if (/(itemselect)/.test(protoParams[item])) {
              let params = _.isString(protoOptions[item]) ? Options[protoOptions[item]] : protoOptions[item]
              return (
                <FormItem 
                  label={(<span style={{ width: 80, display: 'inline-block' }}>{item}</span>)}
                  >
                  {getFieldDecorator(item, {
                    
                  })(
                    <ItemSelect items={items} />
                  )}
                </FormItem>
              )
            }
            else if (/(string|uid|content)/.test(protoParams[item])) {
              let params = _.isString(protoOptions[item]) ? Options[protoOptions[item]] : protoOptions[item]
              return (
                <FormItem 
                  label={(<span style={{ width: 80, display: 'inline-block' }}>{item}</span>)}
                  required={false}
                  >
                  {getFieldDecorator(item, {
                    //rules: !/^(\!)/.test(protoParams[item]) ? [{ required: true, message: `${item} 不能为空!` }] : []
                    //initialValue: ''
                  })(
                    _.has(protoOptions, item) ? (
                      <Select 
                        placeholder={`请选择 ${item}...`}
                        size="Small"
                        //mode="multiple"
                        style={{ width: 150 }}
                        >
                        {_.keys(params).sort().map((key, i) => {
                          return (
                          <Option key={i} value={key}>{params[key]}</Option>
                          )
                        })}
                      </Select>
                    ) :  (/(content)/.test(protoParams[item]) ? (
                        <TextArea style={{ width: 500 }} rows={4}/>
                      ): (
                        <Input style={{ width: 500 }} />
                      )
                    )
                  )}
                </FormItem>
              )
            }
            else if (/(int)/.test(protoParams[item])) {
              let params = _.isString(protoOptions[item]) ? Options[protoOptions[item]] : protoOptions[item]
              return (
                <FormItem 
                  label={(<span style={{ width: 80, display: 'inline-block' }}>{item}</span>)}
                  required={false}
                  >
                  {_.has(protoOptions, item) 
                    ? getFieldDecorator(item, {
                      //rules: !/^(\!)/.test(protoParams[item]) ? [{ required: true, message: `请选择 ${item} !` }] : []
                      //initialValue: 0
                    })(
                      <Select 
                        placeholder={`请选择 ${item}...`}
                        size="Small"
                        //mode="multiple"
                        style={{ width: 150 }}
                        >
                        {_.keys(params).map((key, i) => {
                          return (
                          <Option key={i} value={key}>[{key}] {params[key]}</Option>
                          )
                        })}
                      </Select>
                    ) 
                    : getFieldDecorator(item, {
                      initialValue: 0
                    })(
                      <InputNumber />
                    )
                  }
                </FormItem>
              )
            }
            else if (/(date|time)/.test(protoParams[item])) {
              let dateOptions = { format: 'YYYY-MM-DD' }
              if (/(time)/.test(protoParams[item])) {
                dateOptions = {
                  ...dateOptions,
                  showTime: { format: 'HH:mm' },
                  format: 'YYYY-MM-DD HH:mm'
                }
              }
              return (
                <FormItem 
                  label={(<span style={{ width: 80, display: 'inline-block' }}>{item}</span>)}
                  required={false}
                  >
                  {getFieldDecorator(item, {
                    rules: !/^(\!)/.test(protoParams[item]) ? [{ required: true, message: `${item} 不能为空!` }] : []
                    //initialValue: 0
                  })(
                    <DatePicker
                      {...dateOptions}
                      />
                  )}
                </FormItem>
              )
            }
            else if (/bool/.test(protoParams[item])) {
              let params = _.isString(protoOptions[item]) ? Options[protoOptions[item]] : protoOptions[item]
              return (
                <FormItem
                  label={(<span style={{ width: 80, display: 'inline-block' }}>{item}</span>)}
                  >
                  {getFieldDecorator(item, {
                    initialValue: false
                  })(
                    <RadioGroup>
                    {_.keys(params).map((item, i) => {
                      return (
                        <RadioButton key={i} value={[false, true][item]}>{params[item]}</RadioButton>
                      )
                    })}
                    </RadioGroup>
                  )}
                </FormItem>
              )
            }
          })}
        </div>
        {protoParams && <Divider style={{ marginTop: 0 }} />}
        <Row>
          <Col span={20}>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={postDataPending} 
              //disabled={!this.state.protoName}
              >
              提交测试
            </Button>
          </Col>
          <Col span={4} style={{ textAlign: 'right' }}>
          <Tooltip title="刷新">
              {listData && (
                <Button shape="circle" style={{ border: 0 }} onClick={() => this.props.actions.getlist()}>
                  <Icon type="sync" spin={getListPending} />
                </Button>
              )}
            </Tooltip>
          </Col>
        </Row>
      </Form>
    )
  }

  handleChangeProto = (value) => {
    this.setState({ protoName: value })
  }

  handleSubmit = (e) => {
    e && e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let proto = `${values.proto}?test`
        _.unset(values, 'proto')
        let protoAPI = null
        let protoParams = null
        if (this.state.protoName && this.props.listData) {
          protoAPI = _.find(this.props.listData, o => o.name === this.state.protoName)
          protoParams = protoAPI.params
        }
        for (let item of _.keys(protoParams)) {
          if (/(date)/.test(protoParams[item])) {
            values[item] = moment(values[item]).format('YYYY-MM-DD')
          }
          else if (/(time)/.test(protoParams[item])) {
            values[item] = moment(values[item]).format('YYYY-MM-DD HH:mm:ss')
          }
        }
        if (_.has(values, 'recId')) {
          values['recId'] = _.isEmpty(_.trim(values['recId'])) ? _.trim(values['recId']) : _.trim(values['recId']).split(/\s+/)
        }
        this.props.actions.postData(proto, values, this.props.rtsp_key)
      }
    })
  }
}

@connect(
  state => ({
    auth                : state.Passport.auth,
    teams               : state.Passport.teams,
    //listData            : state.Proto.listData,
    postDataTest        : state.Proto.postDataTest
  }),
  dispatch => ({
    actions: bindActionCreators({ 
      ...protoActions
    }, dispatch)
  })
)
export default class Proto extends PureComponent {

  componentDidMount () {
    //this.props.actions.getlist()
  }

  render () {
    const { location, auth, teams, postDataTest } = this.props
    let PostData = null
    if (postDataTest) {
      PostData = postDataTest.data
    }
    const options = {
      location,
      pageCode: accessFlag.value,
      breadcrumb: [
        { name: '主页', link: '/' },
        { name: '系统工具' },
        { name: '接口测试' }
      ],
    }
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    }
    return (
      <CoreLayout {...options}>
        <AdvancedSearchForm />
        <TextArea rows={20} value={PostData && JSON.stringify(PostData, null, 4)} />
      </CoreLayout>
    )
  }
}